package com.td.client.states;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;

import com.td.client.ClientWindow;
import com.td.client.gui.Frame;
import com.td.client.gui.GameRenderer;
import com.td.client.log.GameplayInfo;
import com.td.client.log.UserActionController;
import com.td.core.communication.obj.GameStateInfo.STATE;
import com.td.core.globals.ObjectsGlobal.TowerType;
import com.td.core.obj.Player;
import com.td.core.obj.TDGame;

public class GameplayState extends State{
	
	private GameRenderer gameRenderer;
	private UserActionController userActionController;
	
	public enum MODE { DEFAULT, ADD_TOWER, TOWER_INFO};
	
	//GUI
	private Frame frame;
	private GameplayInfo gameplayInfo;
	private STATE currentState;
	
	Player player;
	
	public GameplayState(ClientWindow clientWindow, GameContainer gameContainer) {
		super(clientWindow, gameContainer);
		
		int plNumber = clientWindow.getPreGameInfo().getMyPlayer().getNumber();
		this.player = clientWindow.getGame().getPlayers()[plNumber]; 
		this.player.getStats().setName(mainGame.getPreGameInfo().getMyPlayer().getName());
		
		gameplayInfo = new GameplayInfo();
		userActionController = new UserActionController(clientWindow.getCommunication(), player, plNumber, this);
		gameRenderer = GameRenderer.createInstance(clientWindow.getGame(), clientWindow.getPreGameInfo(), gameplayInfo);		
		frame = new Frame(gameContainer, this, player);
	}

	@Override
	public void render(GameContainer gc, Graphics g) throws SlickException {
		gameRenderer.draw(g);
		frame.render(gc, g);
	}

	@Override
	public void update(GameContainer gc, int delta) {
		
		if(!mainGame.getGame().getStateInfo().getCurrentState().equals(currentState)){
			
			currentState = mainGame.getGame().getStateInfo().getCurrentState();
			frame.changeEnabled(currentState);
			setDefaultMode();
		}
		
		frame.update(gc, delta);
		frame.myUpdate();
		
		if(!frame.isOn())
			userActionController.update();
		
		if(isGameEnded(mainGame.getGame()))
			mainGame.setState(Type.STATS);
	}
	
	public boolean isGameEnded(TDGame game) {
		
		boolean end = true;
		
		Player[] players = game.getPlayers();
		for(Player pl : players) {
			end &= pl.isGameOver();
		}
		return end;
	}
	
	public void setMode(MODE mode) {
		userActionController.setMode(mode);
	}
	
	public void setDefaultMode() {
		userActionController.setMode(MODE.DEFAULT);
		frame.unselectButtons();
		gameplayInfo.setAddingTower(null);
		gameplayInfo.setNet(false);
	}
	
	public void setAddingTowerType(TowerType type) {
		
		setMode(MODE.ADD_TOWER);
		userActionController.setAddTowerType(type);
			
	}

	public GameplayInfo getGameplayInfo() {
		return gameplayInfo;
	}

	public void setGameplayInfo(GameplayInfo gameplayInfo) {
		this.gameplayInfo = gameplayInfo;
	}
	
	
	
	

}
